package com.netty.pro.netty.groupChat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * @author xuzn
 * @ClassName: GroupChatClient
 * @ProjectName netty-pro
 * @date 2020/3/15/10:41
 */
public class GroupChatClient {
  private String host;
  private int port;

  public GroupChatClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(group).channel(NioSocketChannel.class)
              .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  // 得到pipeline
                  ChannelPipeline pipeline = ch.pipeline();
                  pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                  pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                  pipeline.addLast(new GroupChatClientHandler());
                }
              });
      ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
      Channel channel = channelFuture.channel();
      System.out.println("~~~~~~" + channel.localAddress() + "~~~~~~");
      // 客户端需要输入
      Scanner scanner = new Scanner(System.in);
      while (scanner.hasNextLine()) {
        String msg = scanner.nextLine();
        channel.writeAndFlush(msg + "\r\n");
      }
    } finally {
      group.shutdownGracefully();
    }
  }

  public static void main(String[] args) throws Exception {
    new GroupChatClient("127.0.0.1", 7000).run();
  }
}
